package com.jeeinc.oa.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeinc.oa.dao.IWeiboUserDao;
import com.jeeinc.oa.dao.IWeiboUserTimelineDao;
import com.jeeinc.oa.domain.MidChangerBO;
import com.jeeinc.oa.domain.Weibo_StatusesBO;
import com.jeeinc.oa.domain.Weibo_User;
import com.jeeinc.oa.domain.Weibo_User_Timeline;
import com.jeeinc.oa.service.IWeiboService;
import com.jeeinc.oa.utils.Constant;
import com.jeeinc.oa.utils.HttpClientUtils;
import com.jeeinc.oa.utils.JsonBinder;

/**
 * @description 动态抓取用户微博消息
 * 
 * @author ynshun
 *
 */
@Service
@Transactional
public class WeiboServiceImpl implements IWeiboService {
	@Resource
	private IWeiboUserTimelineDao weiboTimelineDao;
	@Resource
	private IWeiboUserDao weiboUserDao;
	
	@Scheduled(cron = "0 0/1 * * * ?")
	@Override
	public void loadWeb() {
		try {
			Weibo_StatusesBO bo = JsonBinder.toEntity(HttpClientUtils.get(Constant.WEIBO_GET_USER_TIMELINE_URL), Weibo_StatusesBO.class);
			if (bo == null) {
				throw new Exception("新浪微博获取用户数据错误");
			}
			List<Weibo_User_Timeline> statuses = bo.getStatuses();
			if (statuses == null) {
				throw new Exception("新浪微博获取用户数据错误");
			}
			for (Weibo_User_Timeline tl : statuses) {
				Weibo_User user = weiboUserDao.get(tl.getUser().getId());
				if (user == null) {
					user = tl.getUser();
					weiboUserDao.save(user);
				}
				Weibo_User_Timeline timeline = weiboTimelineDao.get(tl.getId());
				if (timeline == null) {
					timeline = new Weibo_User_Timeline();
					BeanUtils.copyProperties(tl, timeline);
					timeline.setUser(user);
					MidChangerBO mid = JsonBinder.toEntity(HttpClientUtils.get(Constant.WEIBO_GET_MID_CHANGE_URL + timeline.getMid()), MidChangerBO.class);
					timeline.setIdstr(mid.getMid());
					weiboTimelineDao.save(timeline);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
